package com.lagou.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@Component
public class IpFilter implements GlobalFilter, Ordered {

    private static Map<String, Integer> ipMap = new HashMap<>();

    static {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                ipMap.clear();
            }
        }, 0, 1000);
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();
        System.out.println(clientIp);
        Integer count = ipMap.get(clientIp);
        if (count == null){
            ipMap.put(clientIp, 1);
        }else if (count > 100){
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }else {
            ipMap.put(clientIp, count + 1);
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
